package com.zerosky.crm.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.OaMenu;
import com.zerosky.crm.po.Relation;


public class BaseAction extends ApplicationObjectSupport {
	protected HttpServletRequest request = null;
	protected HttpServletResponse response = null;
	protected ServletContext sc = null;
	protected Properties prop = new Properties();

	protected Logger logger = Logger.getLogger("log4j.properties");
	protected static Logger logger1 = Logger.getLogger("log4j.properties");

	@InitBinder
	public void init(HttpSession session, HttpServletRequest request, ServletRequestDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		//dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

	}
	
	protected HttpServletRequest getRequest() {
		request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}

	protected HttpServletResponse getResponse() {

		return (HttpServletResponse) ((ServletResponseWrapper) RequestContextHolder.getRequestAttributes())
				.getResponse();
	}

	protected ServletContext getSc() {
		return sc;
	}

	public static void feedback(HttpServletResponse response, String content) throws IOException {
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");

		PrintWriter writer = response.getWriter();
		writer.write(content);
		writer.flush();
		writer.close();
	}

	public String getProp(HttpServletRequest request, String name) {
		String path = request.getSession().getServletContext().getRealPath("/");
		Properties p = new Properties();// 加载属性文件读取类
		FileInputStream in;
		String url = "";
		try {
			// propertiesFileName如test.properties
			in = new FileInputStream(path + "/WEB-INF/custom.properties");// 以流的形式读入属性文件
			p.load(in);// 属性文件将该流加入的可被读取的属性中
			in.close();// 读完了关闭
			url = p.getProperty(name);// 取得对应的属性值
		} catch (Exception e) {
			e.printStackTrace();
		}

		return url;
	}

	public void setProp(Properties prop) {
		this.prop = prop;
	}

	/**
	 * 找出用户当前所在公司或部门
	 * 
	 * @param emp
	 * @return
	 */
	public static String superiorCompany(Employee emp) {
		if (emp.getDept().getPid() != null) {
			return emp.getDept().getPid();
		} else {
			return emp.getDept().getDeptId();
		}
	}

	/**
	 * 生成菜单
	 * 
	 * @param oaMenu
	 * @param relation
	 * @return
	 */
	public List<OaMenu> shengcMenu(List<OaMenu> oaMenu, List<Relation> relation) {
		for (OaMenu menu : oaMenu) {
			for (Relation rel : relation) {
				if (menu.getId() != null && rel.getOaMenu().getId().equals(menu.getId())) {
					menu.setIsStart(1);
				}
			}
			for (OaMenu menuchilds : menu.getChildMenus()) {
				for (Relation rel : relation) {
					if (menuchilds.getId() != null && rel.getOaMenu().getId().equals(menuchilds.getId())) {
						menuchilds.setIsStart(1);
					}
				}
			}
			int count = 0;
			for (OaMenu menua : menu.getChildMenus()) {
				if (menua.getIsStart() != null && menua.getIsStart() == 1 && menua.getStatus() == 0) {
					count++;
				}
			}
			if (count == 0) {
				menu.setIsStart(0);
			}
		}
		return oaMenu;
	}

	/**
	 * 检查用户是否具有权限
	 * 
	 * @param menuList
	 * @param id
	 * @return
	 */
	public boolean checkPower(HttpSession session, Integer id) {
		List<OaMenu> menuList = (List<OaMenu>) session.getAttribute("menu");
		boolean isCheck = false;
		try {
			for (OaMenu menu : menuList) {
				if (id != null && id.equals(menu.getId()) && menu.getIsStart().equals(1)) {
					isCheck = true;
				}
				for (OaMenu menuchilds : menu.getChildMenus()) {
					if (id != null && id.equals(menuchilds.getId()) && menuchilds.getIsStart() !=null && menuchilds.getIsStart().equals(1)) {
						isCheck = true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			isCheck = false;
		}
		return isCheck;
	}

	/**
	 * 转换json字符串
	 */
	public static String toJson(Map map) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		// 转化为json字符串
		String json = objectMapper.writeValueAsString(map);
		return json;
	}

	public static Date stringToDate(String date) {
		SimpleDateFormat formatter;
		try {
			formatter = new SimpleDateFormat("yyyy-MM-dd");
			Date ctime = formatter.parse(date);
			return ctime;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	public static Date stringToDateTime(String date) {
		SimpleDateFormat formatter;
		try {
			formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date ctime = formatter.parse(date);
			return ctime;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	/**
	 * 格式化时间
	 * @param date
	 * @return
	 */
	public static String dateTimeToString(Date date) {
		SimpleDateFormat formatter;
		try {
			formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String ctime = formatter.format(date);
			return ctime;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	/**
	 * 格式化时间
	 * @param date
	 * @return
	 */
	public static String dateToString(Date time) {
		SimpleDateFormat formatter;
		try {
			formatter = new SimpleDateFormat("yyyy-MM-dd");
			String ctime = formatter.format(time);
			return ctime;
		} catch (Exception e) {
			return null;
		}

	}
	/**
	 * 根据IP获取登录地址
	 * @param strIP
	 * @return
	 */
	public String getAddressByIP(String strIP)  
	{   
	  try  
	  {  
	    //String strIP = "0.0.0.0";  
	    URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + strIP);   
	    URLConnection conn = url.openConnection();   
	    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));   
	    String line = null;   
	    StringBuffer result = new StringBuffer();   
	    while((line = reader.readLine()) != null)  
	    {   
	      result.append(line);   
	    }   
	    reader.close();   
	    strIP = result.substring(result.indexOf( "该IP所在地为：" ));  
	    strIP = strIP.substring(strIP.indexOf( "：") + 1);  
	    String province = strIP.substring(6, strIP.indexOf("省"));  
	    String city = strIP.substring(strIP.indexOf("省") + 1, strIP.indexOf("市"));
		return city; 
	  }  
	  catch( IOException e)  
	  {   
	    return "读取失败";   
	  }
	}  
	private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }
	public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            //关闭输入流
            is.close();
        }
    }
	public static String getAddrName(String url) throws JSONException, IOException{
        //这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
        JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=E9OF9GCmhZM5b4zQtF5q6vp5AcGByh8l&ip="+url);
        /* 获取到的json对象：
         *         {"address":"CN|河北|保定|None|UNICOM|0|0",
         *        "content":{"address_detail":{"province":"河北省","city":"保定市","street":"","district":"","street_number":"","city_code":307},
         *        "address":"河北省保定市","point":{"x":"12856963.35","y":"4678360.5"}},
         *        "status":0}
        */

        JSONObject content=json.getJSONObject("content");              //获取json对象里的content对象
        //JSONObject addr_detail=content.getJSONObject("address");//从content对象里获取address_detail
        String city=content.get("address").toString();                //获取市名，可以根据具体需求更改，如果需要获取省份的名字，可以把“city”改成“province”...
        return city;
    }
	/** 
     * 获取当前网络ip 
     * @param request 
     * @return 
     */  
    public String getIpAddr(HttpServletRequest request){  
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    }
      
	public static String getMyIP() throws IOException {  
		String ip = "";
		String chinaz = "http://ip.chinaz.com";
		
		StringBuilder inputLine = new StringBuilder();
		String read = "";
		URL url = null;
		HttpURLConnection urlConnection = null;
		BufferedReader in = null;
		try {
			url = new URL(chinaz);
			urlConnection = (HttpURLConnection) url.openConnection();
		    in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
			while((read=in.readLine())!=null){
				inputLine.append(read+"\r\n");
			}
			//System.out.println(inputLine.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		
		Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
		Matcher m = p.matcher(inputLine.toString());
		if(m.find()){
			String ipstr = m.group(1);
			ip = ipstr;
			//System.out.println(ipstr);
		}
		return ip;
    } 
}
